// pages/content/payment.js
var app = getApp();
var rsa = require('../../utils/rsa.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    inputnumber: '',
    items: [
      { pay_name: '支付宝', pay_type: '支付宝' },
      { pay_name: '微信', pay_type: '微信',},
      { pay_name: '银联', pay_type: '银联' },
      { pay_name: '现金', pay_type: '现金' },
      
    ],
    goodList: [],  // var good = {goodbtn:'',num:1,name:'',price:0.00};
    huyflag:false,

    inpttext:'',   //会员到店输入
    vipArr_title:'',  //会员到店提示
    vipdetail:'',  //vip详情
    select_paytpye:0,   //支付方式
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const tel = options.tel;
    if(tel){
      this.viprequest(tel);
    }
    this.checkPaytype();
  },
//查询支付类型
  checkPaytype:function(){
    var that = this;
    var shopnum = app.globalData.shoopnum;
    const setion = app.globalData.session;
    wx.showLoading({
      title: '请求中...',
      mask: true,
    })
    
    rsa.htp('order.paytype', {"session_id": setion}, (err, res) => {
      wx.hideLoading();
      if (err) {
       wx.showToast({
         title: err,
         icon:'none',
         duration:3000,
       })
        return;
      }
      that.setData({
        items: res.data.pay_list,
        select_paytpye: res.data.pay_list[0].pay_type,
      })
      
    
    })
  },
  radioChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.setData({
      select_paytpye: e.detail.value,
    })
  },
  //会员到店
  viparrive:function(){
    this.setData({
      huyflag: true,
    })
  },
  hidedaod:function(){
    this.setData({
      huyflag: false,
      vipArr_title: '',
    })
  },
  //确定
  userArrive:function(){
    const tel = this.data.inpttext;
    if (!tel) {
      this.setData({
        vipArr_title: '手机号不为空',
      })
    } else {
      this.setData({
        vipArr_title: '处理中...',
      })
      this.viprequest(tel);
     
    }
  },
  viprequest:function(e){
    var shopnum = app.globalData.shoopnum;
    const setion = app.globalData.session;
    wx.showLoading({
      title: '请求中...',
      mask: true,
    })
    rsa.Cpic_fetchPost(rsa.SERVERPORT, {
      'method': 'promotion.member_regist', "seller_bn": shopnum, "session_id": setion, "mobile": e
    }, (err, res) => {
      wx.hideLoading();
      if (err) {
        this.setData({
          vipArr_title: err,
        })
        return;
      }
      this.setData({
        vipdetail: res.data, //vip详情
        vipArr_title: '',
        huyflag: false,
        inputnumber: '',
        goodList: [],
      })
    })
  },
  inpaction:function(e){
    this.setData({
      inpttext:e.detail.value,
      vipArr_title:'',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
 
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //键盘组建
  keynumberAction: function (e) {
    var oragin = this.data.inputnumber;
    const current = e.currentTarget.dataset.info;
    var nowp = oragin + current.toString();
    this.setData({
      inputnumber: nowp,
    })
  },
  scanAction: function () {
    var that = this;
    var goods = that.data.goodList;
    var mp = that.data.inputnumber ? that.data.inputnumber : '0';
    wx.scanCode({
      success: (res) => {
        this.requestGoodsDetail(res.result);
      }
    })
  },
  //delete  
  reduceAction: function () {
    var oragin = this.data.inputnumber;
    var temp = oragin.substring(0, oragin.length - 1);
    this.setData({
      inputnumber: temp,
    })
  },
  reducegoodsAction: function (e) {
    var mp = this.data.inputnumber ? this.data.inputnumber : '0';
    const index = e.currentTarget.dataset.info;
    var goods = this.data.goodList;
    var cuen = goods.splice(index, 1);
    var money = cuen[0].price;
    var temp = parseFloat(mp) - parseFloat(money);
    var amont = temp < 0 ? 0 : temp;
    this.setData({
      goodList: goods,
      inputnumber: amont.toString(),
    })
  },
  //下单
  payAction: function () {
    const paytype = this.data.select_paytpye;
    console.log('支付方式：'+paytype);
    const cost = this.data.inputnumber;
    var cvl = parseFloat(cost);
    if (cvl <= 0) {
      return
    }
    this.fastorder();
    
  },
  //无商品下单
  fastorder: function () {
    const shopnum = app.globalData.shoopnum;
    const settion = app.globalData.session;
    var payamount = this.data.inputnumber;
    const vip = this.data.vipdetail;  //vip详情
    var memberid = vip.member_id ? vip.member_id : '';
    var money = (parseFloat(payamount) * 100).toFixed(0);
    wx.showLoading({
      title: '下单中，请稍等',
      mask: true,
    })
    rsa.Cpic_fetchPost(rsa.SERVERPORT, {
      'method': 'order.docreate', "seller_bn": shopnum, 'session_id': settion, "pay_amount": money, 'member_id': memberid,
    }, (err, res) => {
      wx.hideLoading();
      if (!res || res == '') {
        wx.showToast({
          title: err,
          icon: 'none',
          duration: 5000
        })
        return
      }
      var res_data = res.data;
      var oderid = res_data.order_id;
      this.runpayWithOrder(res_data);
    });
  },
  //支付
  runpayWithOrder:function(e){
     const spay = this.data.select_paytpye;
    switch (spay){
      case '1':      //扫码付
        wx.scanCode({
          success: (res) => {
            var vele = res.result;
            this.scanpay(e,vele);
          }
        })
  
      break;
      case '2':    //现金支付
        this.cashpay(e);
      break;
      case '3':    //一卡通支付
        wx.scanCode({
          success: (res) => {
            var vele = res.result;
            this.scanpay(e, vele);
          }
        })
      break;
    }
  },

  //被扫支付
  scanpay: function (st,scode) {
    const shopnum = app.globalData.shoopnum;
    const settion = app.globalData.session;
    const payvalue = st.total_amount;
    var paymont = (parseFloat(payvalue) * 100).toFixed(0);
    if (paymont <= 0) {
      wx.showModal({
        title: '提示',
        content: '实收金额为0，不能收款',
        showCancel: false,
        success: function (res) {
        }
      })
      return;
    }
    const orid = st.order_id
    wx.showLoading({
      title: '支付中...',
      mask: true,
    })
    rsa.Cpic_fetchPost(rsa.SERVERPORT, { 'method': 'orders.micropay', "seller_bn": shopnum, 'session_id': settion, 'order_id': orid, 'pay_amount': paymont, 'auth_code': scode }, (err, res) => {
      wx.hideLoading()
      if (err != '') {
        wx.showModal({
          title: '提示',
          content: err,
          showCancel: false,
          success: function (res) {
          }
        })
        return
      }
      var res_data = res.data;
      var paystatus = res_data.pay_status;
      // 付款状态（0：未支付，1：已支付，3：部分付款，4：部分退款，5：全额退款）
      var temstr = '' //标题
      var notice = '' // 提示
      switch (paystatus) {
        case '0':
          temstr = '收款失败';
          notice = '请重新收款';
          break;
        case '1':
          temstr = '收款完成';
          notice = "已收金额：" + paym + "，返回上个界面";
          break;
        case '3':
          temstr = '部分付款';
          notice = "已收金额：" + paym + ',待收金额：' + repay + '，请继续收款';
          break;
        case '4':
          temstr = '部分退款';
          notice = "已退金额：" + paym;
          break;
        case '5':
          temstr = '全额退款';
          notice = "已退金额：" + paym;
          break;
      }
  
      wx.showModal({
        title: temstr,
        content: notice,
        showCancel: false,
        success: function (res) {
        }
      })
    });

  },


 //现金支付
  cashpay: function (e) {
    const shopnum = app.globalData.shoopnum;
    const settion = app.globalData.session;
    const payvalue = e.total_amount;
    var paymont = (parseFloat(payvalue) * 100).toFixed(0);
    if (paymont <= 0) {
      wx.showModal({
        title: '提示',
        content: '实收金额为0，不能收款',
        showCancel: false,
        success: function (res) {
        }
      })
      return;
    }
    const orid = e.order_id
    wx.showLoading({
      title: '支付中...',
      mask: true,
    })
    rsa.Cpic_fetchPost(rsa.SERVERPORT, { 'method': 'orders.pay_cash', "seller_bn": shopnum, 'session_id': settion, 'order_id': orid, 'pay_amount': paymont }, (err, res) => {
      wx.hideLoading()
      if (err != '') {
        wx.showModal({
          title: '提示',
          content: err,
          showCancel: false,
          success: function (res) {
          }
        })
        return
      }
      var res_data = res.data;
      if (!res_data) {
        wx.showToast({
          title: res.return_msg,
          icon: 'none',
          duration: 5000
        })
        return;
      }
      var paystatus = res_data.pay_status;
      // 付款状态（0：未支付，1：已支付，3：部分付款，4：部分退款，5：全额退款）
      var temstr = '' //标题
      var notice = '' // 提示
      const repay = res_data.still_amount; //待支付金额
      const paym = payvalue;
      switch (paystatus) {
        case '0':
          temstr = '收款失败';
          notice = '请重新收款';
          break;
        case '1':
          temstr = '收款完成';
          notice = "已收金额：" + paym + "，返回上个界面";
          break;
        case '3':
          temstr = '部分付款';
          notice = "已收金额：" + paym + ',待收金额：' + repay + '，请继续收款';
          break;
        case '4':
          temstr = '部分退款';
          notice = "已退金额：" + paym;
          break;
        case '5':
          temstr = '全额退款';
          notice = "已退金额：" + paym;
          break;
      }
      
      wx.showModal({
        title: temstr,
        content: notice,
        showCancel: false,
        success: function (res) {
          if (temstr == "收款完成") {
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
    });
  },



})